#include <stdio.h>
#include <stdlib.h>
#include <vector>

int maxProfit(std::vector<int> &prices) {
    if(prices.size() <= 1)
    {
        return 0;
    } 
    const int BUY = 1;//1 for buy -1 for sell
    const int SELL = -1;        
    int profit = 0;
    int pre = 0;
    int cur = 0;
    int operation = BUY; 
    
    std::vector<int>::iterator it;
    for (it = prices.begin()+1; it != prices.end() ; ++it)
    {
        if (*it > *(it - 1))
        {
            pre = cur;
            cur = 1;
        }
        else if (*it < *(it - 1))
        {
            pre = cur;
            cur = -1;
        }
        else
        {
            pre = cur;
            cur = 0;
        }

        if (pre < cur && cur == 1 && operation == BUY)
        {
            printf("valley %d pre %d cur %d\n", it - prices.begin() -1, pre, cur);
            profit -= *(it - 1);
            operation = SELL;
        }
        if (pre > cur && cur == -1 && operation == SELL)
        {
            printf("peak %d pre %d cur %d \n", it - prices.begin() -1, pre, cur);
            profit += *(it -1);
            operation = BUY;
        }
    }
    if (cur == 1 && operation == SELL)
    {
        profit += *(--it);
    }
    return profit;
}

int main(int argc, char const *argv[])
{
    int myarray[] = {1,1,0};
    std::vector<int> v(myarray, myarray + sizeof(myarray)/sizeof(int));
    printf("%d\n", maxProfit(v));
    return 0;
}
